//
//  HXNowJobWeekViewController.m
//  KD
//
//  Created by ifly on 16/5/29.
//  Copyright © 2016年 Whx. All rights reserved.
//

#define DateLabelWith 50
#define Gap 10
#define BtnWith HXSCREEN_WIDTH - 20 - DateLabelWith
#define BtnHeight 38

#import "HXNowJobWeekViewController.h"
//#import "HXPictureGatherViewController.h"
#import "HXSitePictureViewController.h"
#import "NSString+Frame.h"
#import "Imitation_AlertView_TextField.h"//模拟AlertView

@interface HXNowJobWeekViewController ()<Imitation_AlertView_TextFielddelegate>
@property(nonatomic,strong) UILabel *dateLabel;
@property(nonatomic,weak) UIView *amView;
@property(nonatomic,weak) UIView *pmView;
@property(nonatomic,strong) UILabel *amLabel;
@property(nonatomic,strong) UILabel *pmLabel;
@property(nonatomic,strong) UIButton *amAddBtn;
@property (nonatomic,strong) UIButton * amChangeBtn;
@property(nonatomic,strong) UIButton *pmAddBtn;
@property (nonatomic,strong) UIButton * pmChangeBtn;
@property(nonatomic,assign) BOOL amJobContent;
@property(nonatomic,assign) BOOL pmJobContent;

//模拟AlertView
@property (nonatomic,strong) Imitation_AlertView_TextField * alertView;
//@property (nonatomic,strong) Imitation_AlertView_TextField * pm_alertView;
//@property (nonatomic,strong) Imitation_AlertView_TextField * am_change_alertView;
//@property (nonatomic,strong) Imitation_AlertView_TextField * pm_change_alertView;


@end

@implementation HXNowJobWeekViewController

- (void)setModel:(HXJopRecordListModel *)model{
    _model = model;
    self.amJobContent = NO;
    self.pmJobContent = NO;
    if ([GlobalUtil isNilValue:model.CreateDate]) {
        self.dateLabel.text = [NSString stringWithFormat:@"%@ ",model.Week];
    }else{
        self.dateLabel.text = [NSString stringWithFormat:@"%@      %@",model.CreateDate,model.Week];
    }
//    self.amView.backgroundColor = [UIColor redColor];
//    self.pmView.backgroundColor = [UIColor orangeColor];
    [self.amView removeFromSuperview];
    [self.pmView removeFromSuperview];
    [self addAMView];
    [self addPMView];
//    [self addLineView];
    
//    self.amView.backgroundColor = HXRandomColor;
//    self.pmView.backgroundColor = HXRandomColor;
//    self.view.backgroundColor = HXRandomColor;

    
    if (_alertView == nil) {
        
        _alertView = [[Imitation_AlertView_TextField alloc] initWithFatherViewFrameWidth:self.superVc.view.width withFrameHeight:self.superVc.view.height];
        [_alertView viewHidden];
        _alertView.delegate = self;
    }
    
    self.myHeight = self.pmView.bottom + Gap +1;
}

-(void)addAMView{
    UIView *amView = [[UIView alloc]init];
    [self.view addSubview:amView];
    self.amView = amView;
    [self.amView addSubview:self.amLabel];
    if ([self.model.isMy isEqualToString:@"yes"] || [self.model.Work_AMText isEqualToString:@"-1"]) {//自己添加的模型 这时只需要一个添加按钮
        self.amJobContent = YES;
        _amAddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [ _amAddBtn setFrame:CGRectMake(DateLabelWith + Gap, 0, BtnWith, BtnHeight)];
        _amAddBtn.layer.borderWidth = 1;
        _amAddBtn.titleLabel.numberOfLines = 0;
        _amAddBtn.layer.borderColor = MAINCOLOR.CGColor;
        [_amAddBtn setTitle:@"添加工作记录" forState:UIControlStateNormal];
        [_amAddBtn setTitleColor:MAINCOLOR forState:UIControlStateNormal];
        [_amAddBtn addTarget:self action:@selector(amAddbtnClick) forControlEvents:UIControlEventTouchUpInside];
        _amAddBtn.layer.cornerRadius = 8;
        _amAddBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        
        _amAddBtn.tag = 10000;
        [self.amView addSubview:_amAddBtn];
        self.amView.frame = CGRectMake(0, CGRectGetMaxY(self.dateLabel.frame) + Gap, HXSCREEN_WIDTH, BtnHeight);
        return;
    }
    CGFloat siteY = 0;//工地现场的高度
    for (HXJopRecordSiteListModel *amModel in self.model.AMList) {
        if([amModel.TaskType isEqualToString:@"1"]){//工地工作
            
            CGFloat height = [[NSString stringWithFormat:@"%@%@",amModel.SiteName,amModel.HasPunish] heightWithFont:[UIFont systemFontOfSize:14] withinWidth:BtnWith - 8];
            height = height > BtnHeight ? height : BtnHeight;
            CGRect rect = CGRectMake(DateLabelWith + Gap,siteY, BtnWith, height);
            siteY = siteY + height + Gap;//改变View高度 是下一个按钮的y   
            UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            btn.titleLabel.numberOfLines = 0;
            btn.layer.borderWidth = 1;
            btn.layer.borderColor = MAINCOLOR.CGColor;
            btn.layer.cornerRadius = 8;
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
            [btn addTarget:self action:@selector(goSiteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = [amModel.TaskID integerValue];
            [btn setFrame:rect];
            [btn setTitle:[NSString stringWithFormat:@"%@%@",amModel.SiteName,amModel.HasPunish] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
            [self.amView addSubview:btn];
            btn.backgroundColor = MAINCOLOR;
        }
    }
    CGFloat otherY = 0;//文字工作的高度
    for (HXJopRecordSiteListModel *amModel in self.model.AMList) {
        if ([amModel.TaskType isEqualToString:@"2"]) {//文字工作  只有一个
            self.amJobContent = YES;
            CGSize size= [self SizeWithString:[NSString stringWithFormat:@"%@%@",amModel.SiteName,amModel.HasPunish]];
            _amChangeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            _amChangeBtn.layer.borderWidth = 1;
            _amChangeBtn.layer.borderColor = MAINCOLOR.CGColor;
            _amChangeBtn.layer.cornerRadius = 8;
            _amChangeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
            _amChangeBtn.titleLabel.numberOfLines = 0;
            NSString *str = [NSString stringWithFormat:@"%@%@",amModel.SiteName,amModel.HasPunish];
            if (![GlobalUtil isNilValue:str]) {
                [_amChangeBtn setTitle:str forState:UIControlStateNormal];
            }else{
                [_amChangeBtn setTitle:@"暂无,请添加" forState:UIControlStateNormal];
            }
            [_amChangeBtn setTitleColor:MAINCOLOR forState:UIControlStateNormal];
            [_amChangeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
            [_amChangeBtn addTarget:self action:@selector(changeAmWorkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            _amChangeBtn.tag = [amModel.TaskID integerValue];
            otherY = size.height;
            if (otherY < BtnHeight) otherY = BtnHeight;
            [_amChangeBtn setFrame:CGRectMake(DateLabelWith + Gap, siteY, BtnWith, otherY)];
//            btn.backgroundColor = [UIColor yellowColor];
            [self.amView addSubview:_amChangeBtn];
        }
    }
    
    if (self.amJobContent == NO) {
        self.amJobContent = YES;
        [self.amView addSubview:self.amAddBtn];
//        self.amAddBtn.backgroundColor = [UIColor blackColor];
        [ self.amAddBtn setFrame:CGRectMake(DateLabelWith + Gap, siteY + otherY  , BtnWith, BtnHeight)];
        otherY = otherY + BtnHeight;
    }
    self.amView.frame = CGRectMake(0, CGRectGetMaxY(self.dateLabel.frame)+Gap, HXSCREEN_WIDTH, siteY + otherY  + Gap);
}

-(void)addPMView{
    UIView *pmView = [[UIView alloc]init];
    [self.view addSubview:pmView];
    self.pmView = pmView;
    [self.pmView addSubview:self.pmLabel];
    if ([self.model.isMy isEqualToString:@"yes"] || [self.model.Work_PMText isEqualToString:@"-1"]) {//自己添加的模型 这时只需要一个添加按钮
        self.pmJobContent = YES;
        _pmAddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [ _pmAddBtn setFrame:CGRectMake(DateLabelWith + Gap, 0, BtnWith, BtnHeight)];
        _pmAddBtn.layer.borderWidth = 1;
        _pmAddBtn.titleLabel.numberOfLines = 0;
        _pmAddBtn.layer.borderColor = MAINCOLOR.CGColor;
        [_pmAddBtn setTitle:@"添加工作记录" forState:UIControlStateNormal];
        [_pmAddBtn setTitleColor:MAINCOLOR forState:UIControlStateNormal];
        [_pmAddBtn addTarget:self action:@selector(pmAddbtnClick) forControlEvents:UIControlEventTouchUpInside];
        _pmAddBtn.layer.cornerRadius = 8;
        _pmAddBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        
        _pmAddBtn.tag = 10001;
        [self.pmView addSubview:_pmAddBtn];
        self.pmView.frame = CGRectMake(0, CGRectGetMaxY(self.amView.frame) + Gap, HXSCREEN_WIDTH, BtnHeight);
        return;
    }
    CGFloat siteY = 0;//工地现场的高度
    for (HXJopRecordSiteListModel *pmModel in self.model.PMList) {
        if([pmModel.TaskType isEqualToString:@"1"]){//工地工作
            
            
            CGFloat height = [[NSString stringWithFormat:@"%@%@",pmModel.SiteName,pmModel.HasPunish] heightWithFont:[UIFont systemFontOfSize:14] withinWidth:BtnWith - 8];
            height = height > BtnHeight ? height : BtnHeight;
            CGRect rect = CGRectMake(DateLabelWith + Gap,siteY, BtnWith, height);
            siteY = siteY + height + Gap;//改变View高度 是下一个按钮的y

            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            btn.layer.borderWidth = 1;
            btn.titleLabel.numberOfLines = 0;
            btn.layer.borderColor = MAINCOLOR.CGColor;
            btn.layer.cornerRadius = 8;
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
            [btn addTarget:self action:@selector(goSiteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = [pmModel.TaskID integerValue];
            [btn setFrame:rect];
            [btn setTitle:[NSString stringWithFormat:@"%@%@",pmModel.SiteName,pmModel.HasPunish] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
            [self.pmView addSubview:btn];
            btn.backgroundColor = MAINCOLOR;
        }
    }
    CGFloat otherY = 0;//文字工作的高度
    for (HXJopRecordSiteListModel *pmModel in self.model.PMList) {
        if ([pmModel.TaskType isEqualToString:@"2"]) {//文字工作  只有一个
            self.pmJobContent = YES;
            CGSize size= [self SizeWithString:[NSString stringWithFormat:@"%@%@",pmModel.SiteName,pmModel.HasPunish]];
            _pmChangeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            _pmChangeBtn.layer.borderWidth = 1;
            _pmChangeBtn.layer.borderColor = MAINCOLOR.CGColor;
            _pmChangeBtn.layer.cornerRadius = 8;
            _pmChangeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
            _pmChangeBtn.titleLabel.numberOfLines = 0;
            NSString *str = [NSString stringWithFormat:@"%@%@",pmModel.SiteName,pmModel.HasPunish];
            if (![GlobalUtil isNilValue:str]) {
                [_pmChangeBtn setTitle:str forState:UIControlStateNormal];
            }else{
                [_pmChangeBtn setTitle:@"暂无,请添加" forState:UIControlStateNormal];
            }
            [_pmChangeBtn setTitleColor:MAINCOLOR forState:UIControlStateNormal];
            [_pmChangeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
            [_pmChangeBtn addTarget:self action:@selector(changePmWorkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            _pmChangeBtn.tag = [pmModel.TaskID integerValue];
            otherY = size.height;
            if (otherY < BtnHeight) otherY = BtnHeight;
            [_pmChangeBtn setFrame:CGRectMake(DateLabelWith + Gap, siteY, BtnWith, otherY)];
//            btn.backgroundColor = [UIColor yellowColor];
            [self.pmView addSubview:_pmChangeBtn];
        }
    }
    if (self.pmJobContent == NO) {
        self.pmJobContent = YES;
        [self.pmView addSubview:self.pmAddBtn];
        [ self.pmAddBtn setFrame:CGRectMake(DateLabelWith + Gap, siteY + otherY  , BtnWith, BtnHeight)];
        otherY = otherY + BtnHeight;
    }
    self.pmView.frame = CGRectMake(0, self.amView.bottom + Gap, HXSCREEN_WIDTH, siteY + otherY  + Gap);

}

-(void)addLineView{
    UIView *lineView = [[UIView alloc]init];
    lineView.frame = CGRectMake(10, CGRectGetMaxY(self.pmView.frame) +1, HXSCREEN_WIDTH - 20, 1);
    [self.view addSubview:lineView];
    lineView.backgroundColor = [UIColor lightGrayColor];
}

-(void)goSiteBtnClick:(UIButton *)btn{
    [self.superVc goSiteWithTaskId:[NSString stringWithFormat:@"%ld",(long)btn.tag] createDate:self.model.CreateDate];
}

-(void)changeAmWorkBtnClick:(UIButton *)btn{
    [self loadCreateAlertViewWithTag:_amChangeBtn withTitle:@"上午工作内容" withMessage:btn.titleLabel.text];
    
}

-(void)changePmWorkBtnClick:(UIButton *)btn{
    [self loadCreateAlertViewWithTag:_pmChangeBtn withTitle:@"下午工作内容" withMessage:btn.titleLabel.text];

}

-(CGSize)SizeWithString:(NSString*)str
{
    UIFont *strfont = [UIFont systemFontOfSize:15];
    NSDictionary *dict = @{NSFontAttributeName:strfont};
    CGSize maxSize = CGSizeMake(BtnWith, MAXFLOAT);
    CGSize size = [str boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    return size;
}


#pragma mark - 懒加载
- (UILabel *)dateLabel{
    if (_dateLabel == nil) {
        _dateLabel = [[UILabel alloc]init];
        _dateLabel.frame = CGRectMake(Gap, 0, HXSCREEN_WIDTH - 2*Gap, 40);
        _dateLabel.layer.cornerRadius = 5;
        _dateLabel.layer.masksToBounds = YES;
        _dateLabel.layer.borderColor = MAINCOLOR.CGColor;
        _dateLabel.textColor = [UIColor blackColor];
        _dateLabel.font = [UIFont systemFontOfSize:16];
        _dateLabel.backgroundColor = [UIColor whiteColor];
        self.dateLabel = _dateLabel;
        [self.view addSubview:_dateLabel];
    }
    return _dateLabel;
}

- (UILabel *)amLabel{
    if (_amLabel == nil) {
        _amLabel = [[UILabel alloc]init];
        _amLabel.font = [UIFont systemFontOfSize:15];
        _amLabel.backgroundColor = MAINCOLOR;
        _amLabel.text = @"上午";
        _amLabel.textColor = [UIColor whiteColor];
        _amLabel.textAlignment = NSTextAlignmentCenter;
        _amLabel.frame = CGRectMake(10, 0, 40, BtnHeight);
        self.amLabel = _amLabel;
    }
    return _amLabel;
}

- (UILabel *)pmLabel{
    if (_pmLabel == nil) {
        _pmLabel = [[UILabel alloc]init];
        _pmLabel.font = [UIFont systemFontOfSize:15];
        _pmLabel.backgroundColor = MAINCOLOR;
        _pmLabel.text = @"下午";
        _pmLabel.frame = CGRectMake(10, 0, 40, BtnHeight);
        _pmLabel.textAlignment = NSTextAlignmentCenter;
        _pmLabel.textColor = [UIColor whiteColor];
        self.pmLabel = _pmLabel;
    }
    return _pmLabel;
}

-(UIButton *)amAddBtn{
    if (_amAddBtn == nil) {
        _amAddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [ _amAddBtn setFrame:CGRectMake(DateLabelWith + Gap, 0, BtnWith, BtnHeight)];
        _amAddBtn.layer.borderWidth = 1;
        _amAddBtn.titleLabel.numberOfLines = 0;
        _amAddBtn.layer.borderColor = MAINCOLOR.CGColor;
        [_amAddBtn setTitle:@"添加工作记录" forState:UIControlStateNormal];
        [_amAddBtn setTitleColor:MAINCOLOR forState:UIControlStateNormal];
        [_amAddBtn addTarget:self action:@selector(amAddbtnClick) forControlEvents:UIControlEventTouchUpInside];
        _amAddBtn.layer.cornerRadius = 8;
        _amAddBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        
        _amAddBtn.tag = 10000;
    }
    return _amAddBtn;
}

- (UIButton *)pmAddBtn{
    if (_pmAddBtn == nil) {
        _pmAddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [ _pmAddBtn setFrame:CGRectMake(DateLabelWith + Gap, 0, BtnWith, BtnHeight)];
        _pmAddBtn.layer.borderWidth = 1;
        _pmAddBtn.titleLabel.numberOfLines = 0;
        _pmAddBtn.layer.borderColor = MAINCOLOR.CGColor;
        [_pmAddBtn setTitle:@"添加工作记录" forState:UIControlStateNormal];
        [_pmAddBtn setTitleColor:MAINCOLOR forState:UIControlStateNormal];
        [_pmAddBtn addTarget:self action:@selector(pmAddbtnClick) forControlEvents:UIControlEventTouchUpInside];
        _pmAddBtn.layer.cornerRadius = 8;
        _pmAddBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        
        _pmAddBtn.tag = 10001;
    }
    return _pmAddBtn;
}

-(void)amAddbtnClick{
    [self loadCreateAlertViewWithTag:_amAddBtn withTitle:@"上午工作内容" withMessage:nil];
}

-(void)pmAddbtnClick{
    [self loadCreateAlertViewWithTag:_pmAddBtn withTitle:@"下午工作内容" withMessage:nil];
}

/**
 调用 填写日报的方法 1.tag值  2.提示信息 3.标题
 */
-(void)loadCreateAlertViewWithTag:(UIButton *)button withTitle:(NSString *)title withMessage:(NSString *)message{

    [_alertView viewShow];
    _alertView.tag = button.tag;
    _alertView.title = title;
    if (message.length != 0) {
        _alertView.textMessage = message;
    }
}

// 模拟AlertView的 代理方法 Imitation_AlertView_TextFielddelegate
-(void)at_textViewDidEndEditingWithView:(UIView *)alertView withTextView:(UITextView *)at_textView{

    //NSLog(@"---------- at_textView is %@",at_textView.text);
    NSString * textStr = at_textView.text;
    if (alertView.tag == 10001) {
        if ([GlobalUtil isNilValue:self.model.ID]) {
            self.model.ID = self.weekId;
        }
        [SVProgressHUD showWithStatus:@"正在添加"];
        [NetworkAPI addJobRecordWithWorkID:self.model.ID
                                CreateDate:[NSString stringWithFormat:@"%@ 13:00",self.model.CreateDate]
                           SiteWorkContent:textStr
                                   Success:^(HXBaseModel *result) {
                                       [SVProgressHUD showSuccessWithStatus:@"添加成功"];
                                       if ([self.weekId isEqualToString:@"0"]) {
                                           [self.superVc firstRefreshNowWeekData];
                                       }
                                       else {
                                           [self.superVc refreshRightWeekData];
                                       }
                                   } failure:^(NSError *err) {
                                       [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                   }];

    }else if (alertView.tag == 10000){
        if ([GlobalUtil isNilValue:self.model.ID]) {
            self.model.ID = self.weekId;
        }
        [SVProgressHUD showWithStatus:@"正在添加" ];
        [NetworkAPI addJobRecordWithWorkID:self.model.ID
                                CreateDate:[NSString stringWithFormat:@"%@ 8:00",self.model.CreateDate]
                           SiteWorkContent:textStr
                                   Success:^(HXBaseModel *result) {
                                       [SVProgressHUD showSuccessWithStatus:@"添加成功"];
                                       if ([self.weekId isEqualToString:@"0"]) {
                                           [self.superVc firstRefreshNowWeekData];
                                       }
                                       else {
                                           [self.superVc refreshRightWeekData];
                                       }
                                   } failure:^(NSError *err) {
                                       [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                   }];
    }else if (alertView.tag == _pmChangeBtn.tag){
    
        if ([GlobalUtil isNilValue:self.model.ID]) {
            self.model.ID = self.weekId;
        }
        [SVProgressHUD showWithStatus:@"正在添加" ];
        [NetworkAPI changeJobRecordWithTaskID:[NSString stringWithFormat:@"%ld",(long)_pmChangeBtn.tag]
                              SiteWorkContent:textStr
                                       WorkID:self.model.ID
                                      Success:^(HXBaseModel *result) {
                                          if ([result.code isEqualToString:@"200"]) {
                                              [SVProgressHUD showSuccessWithStatus:@"添加成功"];
                                              if ([self.weekId isEqualToString:@"0"]) {
                                                  [self.superVc firstRefreshNowWeekData];
                                              }
                                              else {
                                                  [self.superVc refreshRightWeekData];
                                              }
                                          }else{
                                              [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                          }
                                          
                                      } failure:^(NSError *err) {
                                          [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                      }];

    }else if (alertView.tag == _amChangeBtn.tag){
    
        if ([GlobalUtil isNilValue:self.model.ID]) {
            self.model.ID = self.weekId;
        }
        [SVProgressHUD showWithStatus:@"正在添加" ];
        [NetworkAPI changeJobRecordWithTaskID:[NSString stringWithFormat:@"%ld",(long)_amChangeBtn.tag]
                              SiteWorkContent:textStr
                                       WorkID:self.model.ID
                                      Success:^(HXBaseModel *result) {
                                          if ([result.code isEqualToString:@"200"]) {
                                              [SVProgressHUD showSuccessWithStatus:@"添加成功"];
                                              if ([self.weekId isEqualToString:@"0"]) {
                                                  [self.superVc firstRefreshNowWeekData];
                                              }
                                              else {
                                                  [self.superVc refreshRightWeekData];
                                              }
                                          }else{
                                              [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                          }
                                          
                                      } failure:^(NSError *err) {
                                          [SVProgressHUD showErrorWithStatus:@"网络错误"];
                                      }];
        
    }
}

- (void)at_textViewDidViewHidden:(UIView *) alertView withTextView:(UITextView *)at_textView {};



@end
